﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Suk.Common;
using Suk.Interface;
using Suk.Models.Config;

namespace Suk.Web
{
    public class Startup
    {
        public static ILoggerRepository loggerRepository { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            loggerRepository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(loggerRepository, new FileInfo("log4net.config"));

            //ILog m_log = LogManager.GetLogger(Startup.loggerRepository.Name, typeof(Startup));

            //m_log.Debug(DateTime.Now.ToLongTimeString()+"这是一个Debug日志");

        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;//这里要改为false，默认是true，true的时候session无效
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            //默认session
            //services.AddDistributedMemoryCache();
            //services.AddSession();

            #region 使用Redis保存Session
            ConnectionConfigModel con = ConfigurationManager.GetAppSettings<ConnectionConfigModel>();

            services.AddDistributedRedisCache(option =>
            {
                //redis 连接字符串
                option.Configuration = con.ConnectionConfig.ConnectionRedis.Connection;
                //redis 实例名
                option.InstanceName = con.ConnectionConfig.ConnectionRedis.InstanceName;
            }
            );

            //添加session 设置过期时长分钟  
            var sessionOutTime = con.ConnectionConfig.ConnectionRedis.SessionTimeOut;
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(Convert.ToDouble(sessionOutTime)); //session活期时间
                options.Cookie.HttpOnly = true;//设为httponly
            });
            #endregion



            services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
      
            services.AddMvc(o =>o.Filters.Add(typeof(GlobalExceptionFilter)))
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var builder = new ContainerBuilder();
            builder.Populate(services);
            builder.RegisterModule<DefaultModule>();

            var Container = builder.Build();
            _container = Container;
            GetFromFac<IDatabaseInterface>().InitDatabase();

            return new AutofacServiceProvider(Container);
        }
        /// <summary>
        /// Autofac容器对象
        /// </summary>
        private static IContainer _container;
        /// <summary>
        /// 从Autofac容器获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            //使用session
            app.UseSession();
            
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

    }
}
